import React, { useState, useEffect } from "react";
import { useLocation } from "react-router";
import { Link } from "react-router-dom";
import axios from "axios";
import {
  BankOutlined,
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PieChartOutlined,
  FormOutlined,
  ApartmentOutlined,
  SnippetsOutlined,
  DiffOutlined,
  OrderedListOutlined,
  CheckOutlined,
  FullscreenExitOutlined,
  BorderOuterOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { Menu, Layout } from "antd";
import "./index.css";
const { Sider } = Layout;

// 数组结构（数据）
// const items = [
//   getItem('首页', '/home', <PieChartOutlined />),
//   getItem('用户管理', '/user-manage', <DesktopOutlined />,[
//     getItem('用户列表','/user-manage/list')
//   ]),
//   getItem('权限管理', '/right-manage', <ContainerOutlined />,[
//     getItem('角色列表','/right-manage/role/list'),
//     getItem('权限列表','/right-manage/right/list'),
//   ]),
//   getItem('新闻管理', 'sub1', <MailOutlined />, [
//     getItem('审核管理', '5'),
//     getItem('发布管理', '6'),
//   ]),
//   getItem('审核管理', 'sub2', <AppstoreOutlined />, [
//     getItem('Option 9', '9'),
//     getItem('Option 10', '10'),
//     getItem('Submenu', 'sub3', null, [getItem('Option 11', '11'), getItem('Option 12', '12')]),
//   ]),,
//   getItem('发布管理', 'sub4', <AppstoreOutlined />, [
//     getItem('Option 9', '13'),
//     getItem('Option 10', '14'),
//     getItem('Submenu', 'sub5', null, [getItem('Option 11', '11'), getItem('Option 12', '12')]),
//   ]),
// ];

export default function SideMenu(props) {
  const {
    role: { rights },
  } = JSON.parse(localStorage.getItem("token"));
  const location = useLocation();
  //得到地址栏中想要的路径，也就是getItem中的key值
  const { pathname } = location;
  const openKeys = ["/" + pathname.split("/")[1]];
  // console.log(openKeys)
  // console.log(location)
  const [menu, setMenu] = useState([]);
  const [collapsed, setCollapsed] = useState(false);
  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };
  // 进行副作用操作，拿到后台提供的数据,这里用的是json-serve的模拟数据，得到他需要用axios.get
  useEffect(() => {
    axios.get("http://localhost:5000/rights?_embed=children").then((res) => {
      setMenu(res.data);
      console.log(res.data);
    });
  }, []);
  function getItem(label, key, icon, children) {
    return {
      key,
      children,
      label,
      icon,
    };
  }
  //手动编写一个图标对象,通过对应的路径进行查找遍历
  const iconMap = {
    "/home": <BankOutlined />,
    "/user-manage": <AppstoreOutlined />,
    "/user-manage/list": <ContainerOutlined />,
    "/right-manage": <DesktopOutlined />,
    "/right-manage/role/list": <MailOutlined />,
    "/right-manage/right/list": <MenuFoldOutlined />,
    "/news-manage": <MenuUnfoldOutlined />,
    "/news-manage/add": <PieChartOutlined />,
    "/news-manage/draft": <FormOutlined />,
    "/news-manage/category": <ApartmentOutlined />,
    "/audit-manage": <SnippetsOutlined />,
    "/audit-manage/audit": <DiffOutlined />,
    "/audit-manage/list": <OrderedListOutlined />,
    "/publish-manage": <CheckOutlined />,
    "/publish-manage/unpublished": <FullscreenExitOutlined />,
    "/publish-manage/published": <BorderOuterOutlined />,
    "/publish-manage/sunset": <DeleteOutlined />,
  };
  //设置角色的权限
  const checkPages = (item) => {
    // console.log(rights)
    // console.log(item.key)
    // 当前用户和当前登陆的用户权限列表;
    return item.pagepermisson && rights.includes(item.key);
  };
  /**假设menuList是后台提供的数据
   * 需要遍历数据进行展示
   * 引入的是antd，按照他的格式来进行展示
   *  */
  function menuListMap(menu) {
    return menu.map((item) => {
      if (item.pagepermisson == "1" && checkPages(item)) {
        // 如果有关联的二级，需要再次遍历一下，并且判断是否有pagepermisson字段，所以需要三目元算符和递归相结合进行，进行筛选和遍历 iconMap[item.key]对应每次遍历的路径，拿到手写的图表对象
        return getItem(
          <Link to={item.key}>{item.label}</Link>,
          item.key,
          iconMap[item.key],
          item.children && item.children.length > 0
            ? menuListMap(item.children)
            : ""
        );
      }
    });
  }
  const items = menuListMap(menu);
  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div style={{ display: "flex", height: "100%", flexDirection: "column" }}>
        <div className="logo">全球新闻发布管理系统</div>
        {/* 设置侧导航超出的话带专属的滚动条 */}
        <div style={{ flex: 1, overflow: "auto" }}>
          <Menu
            // 加default就是变成非受控组件。不加的话就是受控组件，所以去掉default，受控组件可以按照修改的路径进行直接跳转
            selectedKeys={[pathname]} //点击跳转对象的对象,对用key值
            defaultOpenKeys={openKeys} //初始展开的侧单项 要展开的话需要一级路径
            mode="inline"
            theme="dark"
            inlineCollapsed={collapsed}
            items={items} //侧导航的详情
          />
        </div>
      </div>
    </Sider>
  );
}
